import { useModel } from "umi";
import { Popconfirm, Input, List, Space, message } from "antd";
import { useReactive } from "ahooks";

import { AddAdministrator } from "../../_graphql/public";

const AddAdministartorModal = ({ persons, reloadData }) => {
    const { remoteData, graphqlFetchPlatform } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loginInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
        submitLoading: false,
        persons: [],
    });

    const handleSearchMember = async (value) => {
        if (value && loginInfo?.authCenterUrl) {
            state.loading = true;
            let res = await remoteData({
                object: "public-user-auth-center",
                serviceUrl: loginInfo.authCenterUrl,
                serviceName: "/api/v1/person/searchRealName",
                params: { realName: value },
            });
            state.persons = res || [];
            state.loading = false;
        } else {
            message.warning("名称不能为空");
        }
    };

    const add = async (item) => {
        if (item.realNameVerification === false || !item.identityCardNumber) return message.success("未实名认证, 不能添加管理员");
        state.submitLoading = true;
        let res = await graphqlFetchPlatform({
            query: AddAdministrator,
            variables: {
                identityCardNumber: item.identityCardNumber,
                realName: item.realName,
                verifyStatus: false,
            },
        });
        if (res) {
            message.success("成功添加管理员");
            await reloadData();
            onCloseGlobalModal();
        }
        state.submitLoading = false;
    };

    return (
        <Space direction="vertical" size={10} style={{ width: "100%" }}>
            <Input.Search placeholder="搜索人员姓名" onSearch={handleSearchMember} allowClear enterButton />
            <List
                loading={state.loading}
                header={"人员列表"}
                size="small"
                bordered
                dataSource={state.persons}
                renderItem={(item) => (
                    <List.Item
                        actions={[
                            persons?.findIndex((_item) => _item.identityCardNumber === item.identityCardNumber) !== -1 ? (
                                "已添加"
                            ) : (
                                <Popconfirm title="确定要添加当前人员为管理员吗?" okButtonProps={{ loading: state.submitLoading }} placement="topRight" onConfirm={() => add(item)}>
                                    <a>添加</a>
                                </Popconfirm>
                            ),
                        ]}
                    >
                        {item.realName} {state.persons.length > 1 && item.phone && `(${item.phone})`}
                    </List.Item>
                )}
            />
        </Space>
    );
};

export default AddAdministartorModal;
